package com.springboot.service;

import com.springboot.constant.CommonConstant;
import com.springboot.domain.BtEnterprise;
import com.springboot.domain.BtFile;
import com.springboot.domain.Result;
import com.springboot.dto.EnterpriseDetailDTO;
import com.springboot.dto.EnterpriseModifyDTO;
import com.springboot.repository.EnterpriseRepository;
import com.springboot.repository.FileRepository;
import com.springboot.tools.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;
import java.util.List;

/**
 * Created by Administrator on 2017/7/12.
 */
@Slf4j
@Service
@Transactional
public class EnterpriseService{

    @Value("${spring.mail.username}")
    private String username;
    private final EnterpriseRepository enterpriseRepository;
    private FileRepository fileRepository;

    @Autowired
    public EnterpriseService(EnterpriseRepository enterpriseRepository,FileRepository fileRepository) {

        this.enterpriseRepository=enterpriseRepository;
        this.fileRepository = fileRepository;

    }
    public void updateEnterpriseById(EnterpriseModifyDTO enterpriseModifyDTO, HttpSession session) {
            String id = session.getAttribute("user").toString();
            BtEnterprise enterprise=enterpriseRepository.findOne(id);
            BeanUtils.copyProperties(enterpriseModifyDTO, enterprise);
            enterprise.setStatus(CommonConstant.PASS);
            enterpriseRepository.save(enterprise);
    }

    public Result findEnterDetailById(String id) {
        Result<EnterpriseDetailDTO> enterDetails = findEnterDetails(id);
        if (!enterDetails.getABoolean()) {
            return enterDetails;
        }
        int total = enterDetails.getData().getViews() + 1;
        enterpriseRepository.addViews(total, enterDetails.getData().getId());
        return enterDetails;
    }

    public Result findEnterDetails(String id) {
        BtEnterprise enterprise = enterpriseRepository.findOne(id);
        if (enterprise == null) {
            return ResultUtil.error("没有此信息！");
        }
        EnterpriseDetailDTO enterDetailDTO = new EnterpriseDetailDTO();
        BeanUtils.copyProperties(enterprise, enterDetailDTO);
        String ids = fileRepository.findFileId(enterprise.getId(), "headPicture");
        List<BtFile> fileList = fileRepository.findFiles(enterprise.getId());
        enterDetailDTO.setFileList(fileList);
        enterDetailDTO.setIds(ids);
        return ResultUtil.success(enterDetailDTO);
    }
}
